package com.lrm.web.admin;

import com.lrm.po.Pic;
import com.lrm.service.PicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2018/7/17.
 * @Modified By:
 */
@Controller
@RequestMapping("/admin")
public class PicController {
    private static String INPUT="admin/pics-input";
    private static String LIST="admin/pics";


    @Autowired
    private PicService picService;
    //跳转到上传文件的页面
    @GetMapping("pics/input")
    public String goUploadImg(Model model) {
        //跳转到 templates 目录下的 uploadimg.html
        model.addAttribute("pic", new Pic());
        return INPUT;
    }

    //跳转到列表页面
    @GetMapping("pics")
    public String picList(@PageableDefault(size = 10,sort = {"id"},direction = Sort.Direction.DESC)
                                      Pageable pageable, Model model) {
        model.addAttribute("page",picService.listPic(pageable));
        return LIST;
    }
    //处理文件上传
    @PostMapping("pics")
    public String uploadImg(@RequestParam("file") MultipartFile file,
                     HttpServletRequest request ) throws Exception {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上传后的路径
        // 解决中文问题，liunx下中文路径，图片显示问题UUID
        fileName = UUID.randomUUID() + suffixName;
        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
        picService.savePic(file.getBytes(), filePath, fileName);
        return "redirect:/admin/pics";
    }
}
